package ui;

import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import page.PageAnalyzer;
import page.PageParser;
import page.PageRetriever;

/**
 * 
 * @author Vladimir Dudnic, Derek Fleener, Michael Groenier
 * 
 *
 */
public class UI
{
        private PageRetriever retriever;
        private PageAnalyzer analyzer;
        long parse_time;
        long total;
        int limit;
        /**
         * Reads the users input.
         */
        private final Scanner my_console = new Scanner(System.in);
       
        /**
         * Starting URL
         */
       
        private String urlString = "";
       
        public static void main(String args[]) throws InterruptedException, IOException 
        {
                @SuppressWarnings("unused")
				UI ui = new UI();
        }
       /**
        * Constructor for user interface.
        */
        public UI()
        {
                readInputURL();
                boolean correctURL = false;
                while (!correctURL)
                {
                        try 
                        {
                                Jsoup.connect(urlString).get();
                                correctURL = true;
                        } 
                        catch (IllegalArgumentException e) 
                        {
                                System.out.println("Not a valid url, please type in a new one");
                                readInputURL();
                        } 
                        catch (IOException e) 
                        {
                                System.out.println("Not a valid url, please type in a new one");
                                readInputURL();
                        }
                }
                try
                {
                        retriever = new PageRetriever(urlString);
                } 
                catch (IOException e) 
                {
                       
                }
                parse_time = 0;
                analyzer = new PageAnalyzer();
                readInputKeywords();
                long start = System.currentTimeMillis();
                Document currentDoc;
                while (analyzer.getPagesRetrieved() < limit)
                {
                        try
                        {
                                currentDoc = retriever.getNextPage();
                               
                                long parse_start = System.currentTimeMillis();
                                List<String> URLs = PageParser.parseURLs(currentDoc);
                                retriever.addAllPages(URLs);
                                analyzer.addURLs(URLs);
                                List<String> words = PageParser.parseWords(currentDoc);
                                long parse_end = System.currentTimeMillis();
                                parse_time = parse_time + parse_end - parse_start;
                               
                                analyzer.findKeywords(words);
                               
                        } 
                        catch (NoSuchElementException e)
                        {
                                break;
                        }
                }
                long end = System.currentTimeMillis();
                total = end - start;

                printResults();
        }
       

       /**
        * Reads input url
        */
        public void readInputURL() 
        {
                System.out.println("Please type the URL address of where you would like the crawling to begin: ");
                if (my_console.hasNext()) 
                {
                        urlString = my_console.next();
                }
               
        }
       
        /**
         * Reads input keywords 
         */
        private void readInputKeywords() 
        {
                boolean loop = true;
                do
                {
                        System.out.println("Please type a keyword to be searched.");
               
                        if (analyzer.getKeywords().size() <= 10)
                        {
                                analyzer.addKeyword(my_console.next());
                        }
                        System.out.println("Would you like to add more keywords?");
                        System.out.println("Press 1 for yes");
                        System.out.println("Press 2 for no");
                       
                        int next = my_console.nextInt();
                        if (next == 0 || next >= 2) 
                        {
                                loop = false;
                        }

                }
                while (loop);
                System.out.println("Please choose a max number of pages to be crawled");
                limit = my_console.nextInt();
       
        }
       /**
        * Prints the results of the search.
        */
        private void printResults() {
            System.out.println("Pages retrieved: " + analyzer.getPagesRetrieved());
            System.out.println("Average words per page: " + analyzer.getAvgWords());
            System.out.println("Average URLs per page: " + analyzer.getAvgURLs());
            System.out.println("Keyword \t Total hits \t Avg. hits per page");
            String keyword;
            for (int i = 0; i < analyzer.getKeywords().size(); i++) {
                    keyword = analyzer.getKeywords().get(i);
                    System.out.print(keyword + ": \t\t      ");
                    System.out.print(analyzer.getTotalHits(keyword) + "\t\t      ");
                    System.out.println(analyzer.getAvgHits(keyword));
            }
            System.out.println("Average parse time per page: " + (double) parse_time / analyzer.getPagesRetrieved()/1000 + " sec");
            System.out.println("Total running time: " + (double) total/1000 + " sec");
    }

       
       
       
       
}
